import { filterAsyncRouter } from '@/store/modules/permission'
import { changeSystemAPI } from '@/api/system/menu'
import store from '@/store'
import router from '@/router/routers.js'

export const changeMenus = (id = '', next = undefined, to = undefined,) => {
  return new Promise(resolve => {
    changeSystemAPI(id).then(res => {
      const system = store.state.app.systemList.find(item => item.id == id)
      store.dispatch('app/changeSubSystem', system)
      const sdata = JSON.parse(JSON.stringify(res))
      const rdata = JSON.parse(JSON.stringify(res))
      const sidebarRoutes = filterAsyncRouter(sdata)
      const rewriteRoutes = filterAsyncRouter(rdata, false, true)
      rewriteRoutes.push({ path: '*', redirect: '/404', hidden: true })
      store.dispatch('GenerateRoutes', rewriteRoutes).then(() => { // 存储路由
        router.addRoutes(rewriteRoutes) // 动态添加可访问路由表
        !!next && next({ ...to, replace: true })
        resolve()
      })
      store.dispatch('SetSidebarRouters', sidebarRoutes)
      const path = store.state.app.activePath || '/'
      router.push(path)
    }).catch(err => {
      router.push('/login')
    })
  })
}
